package com.haohan.cloud.scm.wecaht.wxapp.core.impl;

import com.haohan.cloud.framework.entity.BaseResp;
import com.haohan.cloud.scm.api.common.BaseApiService;
import com.haohan.cloud.scm.api.common.CommonApiConstant;
import com.haohan.cloud.scm.api.constant.ScmCommonConstant;
import com.haohan.cloud.scm.api.manage.entity.UPassport;
import com.haohan.cloud.scm.api.wechat.req.WechatAddReq;
import com.haohan.cloud.scm.api.wechat.req.WxTenantReq;
import com.haohan.cloud.scm.api.wechat.vo.WxPassportVO;
import com.haohan.cloud.scm.api.wechat.vo.WxTenantVO;
import com.haohan.cloud.scm.common.tools.exception.ErrorDataException;
import com.haohan.cloud.scm.common.tools.util.ScmIncrementUtil;
import com.haohan.cloud.scm.wecaht.wxapp.core.WechatCommonCoreService;
import com.haohan.cloud.scm.wecaht.wxapp.utils.ScmWechatUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author dy
 * @date 2020/5/27
 */
@Service
@AllArgsConstructor
public class WechatCommonCoreServiceImpl implements WechatCommonCoreService {

    private final BaseApiService apiService;
    private final ScmWechatUtils scmWechatUtils;
    private final ScmIncrementUtil scmIncrementUtil;

    @Override
    public WxTenantVO fetchTenantId(WxTenantReq req) {
        // 多租户 uid验证不通过
//        scmWechatUtils.queryUPassportById(req.getUid());
        Map<String, String> map = scmIncrementUtil.fetchMap(ScmCommonConstant.TENANT_MAP_KEY);
        String tenant =  map.get(req.getPmId());
        if(null == tenant){
            throw new ErrorDataException("平台商家id有误");
        }
        int tenantId;
        try{
            tenantId = Integer.parseInt(tenant);
        }catch (Exception e){
            throw new ErrorDataException("平台商家对应租户id有误");
        }
        return new WxTenantVO(tenantId);
    }

    /**
     * 小程序用户通行证获取
     *
     * @param req
     * @return
     */
    @Override
    public WxPassportVO addPassport(WechatAddReq req) {
        BaseResp baseResp = apiService.call(CommonApiConstant.wechat_app_add, req);
        if (baseResp.isSuccess()) {
            UPassport passport = scmWechatUtils.queryUPassportById((String) baseResp.getExt());
            return new WxPassportVO(passport);
        } else {
            throw new ErrorDataException("获取通行证有误：" + baseResp.getMsg());
        }
    }


}
